<?php


namespace App\HttpController;

use EasySwoole\Queue\Job;
use EasySwoole\Http\AbstractInterface\Controller;
use App\Models\AdminModel;
use App\Models\UserModel;
use EasySwoole\Component\Di;
use App\HttpController\UserBase;
use App\Models\Project;
use App\service\MyQueue;
use App\Models\Assign;
use App\Models\FileApp;
use App\Models\History;
class Jg  extends UserBase
{
    
        
    public function onRequest(?string $action): ?bool
    {
        if (!parent::onRequest($action)) {
            return false;
        }


       if(!in_array($this->who['type'],[4,5])){
        
               $this->writeJson(403,"u r not permitted!");
               return false;

       }
        return true;
    }


  function list(){
 
    $limit = \EasySwoole\EasySwoole\Config::getInstance()->getConf('pagelimit');
    $model = Project::create();
    $page = $this->input('page',1);
    $owner = $this->input("owner","");
    $lxnumber = $this->input("lxnumber","");
    $name = $this->input("name","");
    $wtdw = $this->input("wtdw","");
    $bzjg = $this->input("bzjg","");
    $addtime = $this->input("addtime","");
    $industry = $this->input("industry","");
    $wtdwcontactor = $this->input("wtdwlxr","");
    $pslb = $this->input("pslb","");
    $where = [];
    if($owner == 'null'){
        $owner = "";
    }

    if($industry == 'null' || $industry == "1"){
        $industry = "";
    }

    if($lxnumber == 'null'){
        $lxnumber = "";
    }
    if($name == 'null'){
        $name = "";
    }
    if($wtdw == 'null'){
        $wtdw = "";
    }
    if($bzjg == 'null'){
        $bzjg = "";
    }
    if($pslb == 'null'){
        $pslb = "";
    }
    if($wtdwcontactor == 'null'){
        $wtdwcontactor = "";
    }
   

    if($owner){
        $model = $model->where("owner","%".$owner."%",'like');
    }

    if($lxnumber){
   
        $model = $model->where("lxnumber","%".$lxnumber."%",'like');
    }
    if($name){
        $model = $model->where("name","%".$name."%",'like');
    }
    if($wtdw){
        $model = $model->where("wtdw","%".$wtdw."%",'like');
    }
    if($bzjg){
        $model = $model->where("bzjg","%".$bzjg."%",'like');
    }
    
    if($industry){
        $model = $model->where(["industry"=>$industry]);
    }

    if($pslb && $pslb!='1'){
        $model = $model->where(['approve_type'=>$pslb]);
    }
    if($wtdwcontactor){
        $model = $model->where("wtdwcontactor","%".$wtdwcontactor."%",'like');
    }

        $assign_ids = Assign::create()->where(['status'=>1,'assign_eid'=>$this->who['id']])->column('itemid');
        if(!$assign_ids) $assign_ids = [];
        $st = $this->input("st");
        if($st != 'done'){
            $model = $model->where('id',$assign_ids,'in')->where(['status'=>3])->order("id","DESC")->limit($limit * ($page - 1), $limit)->withTotalCount();
            $list = $model->all(null);
            // $list = Project::create()->where('id',$assign_ids,'in')->all(['status'=>3]);
        }else{
            $assign_ids = Assign::create()->where(['status'=>2,'assign_eid'=>$this->who['id']])->column('itemid');
        
            $model = $model->where('id',$assign_ids,'in')->where('status',3,'!=')->order('id', 'DESC')->limit($limit * ($page - 1), $limit)->order('id', 'DESC')->withTotalCount();
            $list = $model->all(null);


        }

        for($i=0;$i<count($list);$i++){

            $list[$i]['isleader'] = Assign::create()->where(['status'=>1,'itemid'=>$list[$i]['id'],'isgroupleader'=>1,'assign_eid'=>$this->who['id']])->get() ? true:false;

        
            $assignusers = Assign::create()->where(['itemid'=>$list[$i]['id'],'status'=>1])->column("assign_eid");

            $logs = History::create()->where(['itemid'=>$list[$i]['id'],'isgroup'=>0,'approveres'=>1,'usertype'=>[[4,5],'in'],'uuid'=>$list[$i]['approveuuid']])->column('userid');

           if($logs == NULL){
               $logs = [];
           }
            if(!array_diff($assignusers, $logs) && !array_diff($logs, $assignusers)){
   
                $list[$i]['canapprove'] = true;

            }else{
                $list[$i]['canapprove'] = false;
            }
        }



        $result = $model->order("id","DESC")->lastQueryResult();
        $total = $result->getTotalCount();
        $pagecon = $this->showPageStringAsAJAX("jumpage",$page,$limit,$total);


        $this->writeJson(200,['list'=>$list,'pg'=>$pagecon]);
  }




  function detail(){
    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $log = History::create()->join('user_list','user_list.id = approve_history.userid')->field(["approve_history.*","user_list.displayname"])->all(['itemid'=>$id]);
    $item  =Project::create()->get(['id'=>$id]);
    for($i=0;$i<count($log);$i++){
        $log[$i]['info'] = UserModel::create()->get(['id'=>$log[$i]['userid']]);
        $log[$i]['file'] = \App\Models\FileApp::create()->all(['approveid'=>$log[$i]['id']]);
    
    
    }
    $this->writeJson(200,['item'=>$item,'log'=>$log]);
  }

  function passitem(){
    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $item  =Project::create()->get(['id'=>$id]);
    if ($item['status'] != 3) {
        $this->writeJson(500,'','this project has a error status');
        return false;
    }
    try {
        // 开启事务
      $isopen  =   \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
        if($data['appres'] == true){
            $status = 4;
        }else{
            $status = -1;
        }
        // 执行更新 $model 的更新操作
        $res = $this->logapprove($this->who['id'],$data['appres'],$id,$data['idea'],0,$this->who['type']);
        
        $file2 = $this->input("files");
      
        if($file2){
            $datafiles = [];
        foreach($file2 as $k=>$v){
            array_push($datafiles,[
                "name"=>$v['filename'],
                "path"=>$v['filepath'],
                "approveid"=>$res,
                "userid"=>$this->who['id'],
                "time"=>time(),
            ]);
        }
   
        \App\Models\FileApp::create()->saveall($datafiles,true,false);
    }
        
        Assign::create()->where(['itemid'=>$id,'uuid'=>$item['approveuuid']])->update(['status'=>2]);
        
        Project::create()->update(['status'=>$status],['id'=>$id]);
        // 提交事务
        \EasySwoole\ORM\DbManager::getInstance()->commit();

        $this->writeJson(200,['code'=>200]);
    } catch(\Throwable  $e){
        // 回滚事务
        \EasySwoole\ORM\DbManager::getInstance()->rollback();
        var_dump($e->getMessage());
    }

  }



  function rejectitem(){

    $data = $this->request()->getRequestParam();
    $id = $data['id'];
    $item  =Project::create()->get(['id'=>intval($id)]);
   
    if ($item['status'] != 0) {
        $this->writeJson(500,'','this project has a error status');
        return false;
    }

    $res = Project::create()->update(['status'=>2],['id'=>$id,'addedby'=>$this->who['id']]);

    $this->writeJson(200,'','ok');

  }


  function passidea(){
    $id = $this->input("id");
    $idea = $this->input("idea");
    try {
        // 开启事务
      $isopen  =   \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
      $res = $this->logapprove($this->who['id'],1,intval($id),$idea,0,$this->who['type']);
      $file2 = $this->input("files");
        
      if($file2){
          $datafiles = [];
      foreach($file2 as $k=>$v){
          array_push($datafiles,[
              "name"=>$v['filename'],
              "path"=>$v['filepath'],
              "approveid"=>$res,
              "userid"=>$this->who['id'],
              "time"=>time(),
          ]);
      }
      FileApp::create()->saveall($datafiles,true,false);
    }


    \EasySwoole\ORM\DbManager::getInstance()->commit();
      $this->writeJson(200,['code'=>200]);

    }catch(\Throwable  $e){
        // 回滚事务
        \EasySwoole\ORM\DbManager::getInstance()->rollback();
        var_dump($e->getMessage());
    }

  }



  function dealitem(){
    $data = $this->request()->getRequestParam();
    $id = intval($data['id']);
    $item  =Project::create()->get(['id'=>$id]);
    if ($item['status'] != 3) {
        $this->writeJson(200,['code'=>500,'msg'=>'this project has a error status'],'this project has a error status');
        return false;
    }
    try {
        // 开启事务
      $isopen  =   \EasySwoole\ORM\DbManager::getInstance()->startTransaction();
        if($data['appres'] == 1){
            $status = 4;
        }else{
            $status = -1;
        }
        // 执行更新 $model 的更新操作
        $appid = $this->logapprove($this->who['id'],$data['appres'],$id,$data['idea'],1,$this->who['type']);
       
        $file2 = $this->input("files");
      
        if($file2){
            $datafiles = [];
        foreach($file2 as $k=>$v){
            array_push($datafiles,[
                "name"=>$v['filename'],
                "path"=>$v['filepath'],
                "approveid"=>$appid,
                "userid"=>$this->who['id'],
                "time"=>time(),
            ]);
        }
   
        \App\Models\FileApp::create()->saveall($datafiles,true,false);
    }

       
        // $assignid = Assign::create()->where(['itemid'=>$id,'assign_eid'=>$this->who['id'],'isgroupleader'=>1,'status'=>1])->column('id');
        
        
        Assign::create()->where(['uuid'=>$item['approveuuid']])->update(['status'=>2],['itemid'=>$id,'status'=>1]);
        
        Project::create()->update(['status'=>$status,'uuid'=>NULL],['id'=>$id]);
        // 提交事务
        \EasySwoole\ORM\DbManager::getInstance()->commit();

        $this->writeJson(200,['code'=>200],"ok");
    } catch(\Throwable  $e){
        // 回滚事务
        \EasySwoole\ORM\DbManager::getInstance()->rollback();
        var_dump($e->getMessage());
        $this->writeJson(404,"error");
    }

  }

   
} 
